package org.jsola.hr.constant.convert;

import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
import org.jsola.common.DateKit8;

import java.math.BigDecimal;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

/**
 * easyExcel导入，日期格式化为: yyyy-MM-dd
 *
 * @author wcl
 */
public class DateConverter implements Converter<Date> {

    @Override
    public Class supportJavaTypeKey() {
        return null;
    }

    @Override
    public CellDataTypeEnum supportExcelTypeKey() {
        return null;
    }

    @Override
    public Date convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration)
            throws Exception {
        // 日期格式无法读取
        if (null == cellData.getStringValue()) {
            BigDecimal numberValue = cellData.getNumberValue();
            if (numberValue == null) {
                return null;
            }
            return formatExcelDate(numberValue.intValue());
        }
        // excel内容
        String stringValue = cellData.getStringValue();
        stringValue = stringValue.replaceAll("/", "-");
        String[] dateArray = stringValue.split("-");

        if (dateArray.length == 3) {
            String year = dateArray[0];
            String month = dateArray[1];
            if (month.length() < 2) {
                month = "0" + month;
            }
            String day = dateArray[2];
            if (day.length() < 2) {
                day = "0" + day;
            }
            String date = year + "-" + month + "-" + day;
            Date date1 = DateKit8.parseDate(date);
            return date1;
        }
        return null;
    }

    @Override
    public CellData convertToExcelData(Date value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration)
            throws Exception {
        return null;
    }

    /**
     * 格式化Excel时间
     *
     * @param day
     * @return yyyy-MM-dd
     */
    private String formatExcelDateStr(int day) {
        Calendar calendar = new GregorianCalendar(1900, 0, -1);
        Date gregorianDate = calendar.getTime();
        return DateKit8.format(DateKit8.addDays(gregorianDate, day), DateKit8.DATE);
    }

    /**
     * 格式化Excel时间
     *
     * @param day 数值型天数
     * @return yyyy-MM-dd
     */
    private Date formatExcelDate(int day) {
        Calendar calendar = new GregorianCalendar(1900, Calendar.JANUARY, -1);
        Date gregorianDate = calendar.getTime();
        return DateKit8.addDays(gregorianDate, day);
    }
}
